package com.sc.nft.task;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.sc.nft.dao.NoticeInfoDao;
import com.sc.nft.dao.PushDao;
import com.sc.nft.dao.StaticDataDao;
import com.sc.nft.entity.NoticeInfo;
import com.sc.nft.entity.Push;
import com.sc.nft.service.PushService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘国航
 * @desc
 * @since 2024/6/15 9:57
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class PushTask {

    private final PushDao pushDao;
    private final NoticeInfoDao noticeInfoDao;
    private final PushService pushService;
    private final StaticDataDao staticDataDao;
    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 推送消息
     */
    @XxlJob("pushTask")
    public void pushTask() {
        List<Push> pushList = pushDao.getUnPushedScheduleListFiveMinuteLater();
        if(CollectionUtil.isEmpty(pushList)) {
            return;
        }
        pushList.forEach(push -> {
            executor.schedule(() -> pushService.doPushMessage(push.getId(), null), calculateDelayInSeconds(push.getSchedulePushTime()), TimeUnit.SECONDS);
        });
    }

    /**
     * 推送公告消息
     */
    @XxlJob("pushNoticeTask")
    public void pushNoticeTask() {
        String pushLimitStartHour = staticDataDao.getByType("push_limit_start_hour").getValue();
        String pushLimitEndHour = staticDataDao.getByType("push_limit_end_hour").getValue();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if(hour < Integer.parseInt(pushLimitEndHour) || hour >= Integer.parseInt(pushLimitStartHour)) {
            return;
        }
        List<NoticeInfo> noticeInfoList = noticeInfoDao.getUnPushedScheduleListFiveMinuteLater();
        if(CollectionUtil.isEmpty(noticeInfoList)) {
            return;
        }
        for(NoticeInfo noticeInfo : noticeInfoList) {
            calendar.setTime(noticeInfo.getStartTime());
            hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour >= Integer.parseInt(pushLimitEndHour) && hour < Integer.parseInt(pushLimitStartHour)) {
                executor.schedule(() -> pushService.doPushNoticeMessage(noticeInfo.getId()), calculateDelayInSeconds(noticeInfo.getStartTime()), TimeUnit.SECONDS);
            }
        }
    }

    private long calculateDelayInSeconds(Date schedulePushTime) {
        return Math.max((schedulePushTime.getTime() - System.currentTimeMillis())/1000, 1L); // 转换为秒
    }


}
